/**
 * Created by quheng on 17/6/22.
 */

var mongodb = require('./db');

function Post(name,title,post){


    this.name  = name ;
    this.title = title;
    this.post = post;
}


module.exports = Post;


Post.prototype.save = function (callback) {

    var date = new Date();
    var time = {
        date:date,
        year:date.getFullYear(),
        month:date.getFullYear()+'-'+(date.getMonth()+1),
        day:date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate(),
        minute:date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+" "+date.getHours()+":"+(date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes())
    }

    //要存入的文档
     var post = {

        name:this.name,
         time :time,
         title:this.title,
         post:this.post
     }

     mongodb.close();
    mongodb.open(function (err,db) {

        if (err){

            return(callback(err));

        }
        //读取post集合
        db.collection('post',function (err,collection) {

            if(err){

                mongodb.close();
                return callback(err);
            }

            //将文档插入post集合

            collection.insert(post,{
                safe:true
            },function (err) {

                mongodb.close();
                if (err){
                    return callback(err);
                }
                callback(null);

            });
        })

    });

}



Post.get = function (name,callback) {


    mongodb.close();
    mongodb.open(function (err,db) {

        if (err){

            return callback(err);

        }

        //读取post collection

        db.collection('post',function (err,collection) {

            if (err){

                mongodb.close();
                return callback(err);
            }

            var query = {};
            if (name != null){

                query.name = name;

                //根据query对象查找文樟

                collection.find(query).sort({

                    time:-1
                }).toArray(function (err,docs) {

                    mongodb.close();
                    if (err){

                        return callback(err); //失败,返回err

                    }

                    callback(null,docs);//成功!以数组的形式返回查询的结果

                });

            }else {

                var posts = new Array();
                callback(null,posts);

            }
        });

    });


}